<?php

/**
 * @author lzp300
 * @copyright 2015-03-26
 */

class osiiOrder extends actionAbstract{
    
    /**
     * 构造函数
     * @var array
     */
    function __construct() {
        parent::__construct();
	    set_time_limit(60);
    }
    
    /**
     * 权限MD5加密
     *   Key //luo2b//uni1001        ID //luo2b  //unibooking
     */
    function SignUtil($serviceName="DomesticSubmitNewHotelOrder",$accountKey="qingmangguokey",$version="1.1.0",$accountID="qingmangguo"){
        $reqTime=date('Y-m-d',time());
        
        $resuoce=array();
        $originalArray=array();
        
        $originalArray['Version']=$version;
        $originalArray['AccountID']=$accountID;
        $originalArray['ReqTime']=$reqTime;
        $originalArray['ServiceName']=$serviceName;
        ksort($originalArray);
        $sortedArray="";
        foreach($originalArray as $k=>$v){
            $sortedArray.=$k.'='.$v.'&';
        }
        $sortedArray=trim($sortedArray,'&');
        $keywords=md5($sortedArray.$accountKey);
        $resuoce['version']=$version;
        $resuoce['accountId']=$accountID;
        $resuoce['serviceName']=$serviceName;
        $resuoce['sign']=$keywords;
        $resuoce['reqTime']=$reqTime;
        //echo "<pre>";print_r($resuoce);exit;
        
        return $resuoce;
    }
    
    function returnHead($status,$responseCode,$responseDescription){
        $resuoce=array();
        $resuoce['status']=$status;
        $resuoce['responseCode']=$responseCode;
        $resuoce['responseDescription']=$responseDescription;
        
        return $resuoce;
    }
    /**
     * 公共调用
     */
    function thall(){
        header("Content-type:text/html;charset=utf-8");
        $arr=$GLOBALS['HTTP_RAW_POST_DATA'];
        
        $arr=json_decode($arr,true);
		
		$logs="初始调用：".json_encode($arr);
		$this->setLogs($logs,"/data/Logs/order/");
		
        //echo "<pre>";print_r($arr);exit;
        $head = $arr['head'];   $body = $arr['body'];
        
        if(empty($head)||empty($body)){
            $errohead=$this->returnHead(4,4000,"报文错误");
            
            $logs="返回数据：".json_encode($errohead)."\r\n接收数据：".json_encode($arr);
            $this->setLogs($logs,"/data/Logs/order/");
            
            echo json_encode(array("head"=>$errohead,"body"=>""));exit;
        }else{
            $myHead=$this->SignUtil($head['serviceName']);
            //print_r($myHead);exit;
            if(array_diff($myHead,$head)){
                $errohead=$this->returnHead(9,4002,"签名验证错误");
                
                $logs="返回数据：".json_encode($errohead)."\r\n接收数据：".json_encode($arr);
                $this->setLogs($logs,"/data/Logs/order/");
                
                echo json_encode(array("head"=>$errohead,"body"=>""));exit;
            }else{
                $apiName=array("DomesticCheckRoomAvail","DomesticSubmitNewHotelOrder","DomesticCancelHotelOrder","DomesticGetOrderStatus","PushOrder");
                if(in_array($head['serviceName'],$apiName)){
                    $thall_code = $this->$head['serviceName']($body,$arr);
                    //print_r($thall_code);exit;
                    
                    $logs="调用方法：".$head['serviceName']."\r\n返回数据：".json_decode(json_encode($thall_code))."\r\n接收数据：".json_encode($arr);
                    $this->setLogs($logs,"/data/Logs/order/");
                    
                    echo $thall_code;exit;
                }else{
                    $errohead=$this->returnHead(9,9010,"服务名称错误或尚未提供指定服务");
                    
                    $logs="返回数据：".json_encode($errohead)."\r\n接收数据：".json_encode($arr);
                    $this->setLogs($logs,"/data/Logs/order/");
                    
                    echo json_encode(array("head"=>$errohead,"body"=>""));exit;
                }
            }
        }
    }
    
    //可订检查接口
    function DomesticCheckRoomAvail($body,$array){
        $arr=array();
        $arr['body']['availQuantity'] = 0;
        $arr['body']['resultCode'] = 0;
        $arr['body']['resultDescript'] = '不可定';
        
        $arr['head']['status'] = 0;
        $arr['head']['responseCode'] = '0000';
        $arr['head']['responseDescription'] = '查询成功';
        
        if(empty($body['hotelCode'])||empty($body['roomTypeCode'])||empty($body['arrivalDate'])||empty($body['departureDate'])||empty($body['roomNumber'])||empty($body['cost'])){
            $arr['head']['status'] = 2;
			$arr['head']['responseCode'] = 2000;
			$arr['head']['responseDescription'] = '数据错误';
			
			return json_encode(array("head"=>$arr['head'],"body"=>$arr['body']));
        }else{
			$this->loadApi('orderapi');
			$orderapi = new orderapi();
			$arPrice=$orderapi->getOrderPrice($body['hotelCode'],$body['roomTypeCode'],$body['roomNumber'],$body['arrivalDate'],$body['departureDate'],$body['cost']);
			$arRoom=$this->selectRooms($body['hotelCode'],$body['roomTypeCode'],$body['arrivalDate'],$body['departureDate'],$body['roomNumber']);
            if($arRoom&&$arPrice){
                $arr['body']['availQuantity'] = $arRoom;
                $arr['body']['resultCode'] = 1;
                $arr['body']['resultDescript'] = '可定';
                
                $arr['head']['status'] = 0;
                $arr['head']['responseCode'] = '0000';
                $arr['head']['responseDescription'] = '查询成功';
            }else{
				$string="";
				if(!$arRoom){$string.="房间不够";}if(!$arPrice){$string.=",价格不正确";}
                $arr['body']['availQuantity'] = $arRoom;
                $arr['body']['resultCode'] = 0;
                $arr['body']['resultDescript'] = $string;
                
                $arr['head']['status'] = 0;
                $arr['head']['responseCode'] = '0000';
                $arr['head']['responseDescription'] = '查询成功';
            }
			
            echo json_encode($arr);
			
			$logs="调用方法：DomesticCheckRoomAvail\r\n返回数据：".json_encode($arr)."\r\n接收数据：".json_encode($array);
			$this->setLogs($logs,"/data/Logs/order/");
			
			exit;
        }
    }
    
    //新订订单接口
    function DomesticSubmitNewHotelOrder($body,$array){
        $this->loadModel('qm','orders');
        
        $arr['head']['status'] = 0;
        $arr['head']['responseCode'] = '0000';
        $arr['head']['responseDescription'] = '操作成功';
		$arRoom=$arPrice=0;
        if(!empty($body['hotelCode'])&&!empty($body['roomTypeId'])&&!empty($body['effectDate'])&&!empty($body['departure'])&&!empty($body['quantity'])&&!empty($body['orderID'])&&!empty($body['sourceID'])&&!empty($body['osiiOtaHotelOrderDetails'])&&is_array($body['osiiOtaHotelOrderDetails'])){
            $price=0;
			foreach($body['osiiOtaHotelOrderDetails'] as $k=>$v){$price+=$v['cost']*$body['quantity'];}
			
			$this->loadApi('orderapi');
			$orderapi = new orderapi();
			$arPrice=$orderapi->getOrderPrice($body['hotelCode'],$body['roomTypeId'],$body['quantity'],$body['effectDate'],$body['departure'],$price);
			$arRoom=$this->selectRooms($body['hotelCode'],$body['roomTypeId'],$body['effectDate'],$body['departure'],$body['quantity']);
		}
		if($arRoom&&$arPrice){
			$data['orderId']    =   $body['orderID'];
			$data['hotelId']    =   $body['hotelCode'];
			$data['roomId']     =   $body['roomTypeId'];
			$data['startDate']  =   $body['effectDate'];
			$data['endDate']    =   $body['departure'];
			$data['price']      =   $price;
			$name = '';
			foreach($body['guests'] as $k=>$v){
				if(isset($v['chinesName'])&&$v['chinesName']){
					if($k == 0){
						$name .= $v['chinesName'];
					}else{
						$name .= ','.$v['chinesName'];
					}
				}else{
					if(isset($v['lastName'])&&$v['lastName']){
						if($k == 0){
							$name .= $v['lastName'];
						}else{
							$name .= ','.$v['lastName'];
						}
					}else{
						if(isset($v['firstName'])&&$v['firstName']){
							if($k == 0){
								$name .= $v['firstName'];
							}else{
								$name .= ','.$v['firstName'];
							}
						}
					}
				}
			}
			$data['type']       =   $body['sourceID'];//渠道编号
			$data['name']       =   $name;//客户姓名
			$data['mobile']     =   $body['mobilePhone'];
			$data['latestTime'] =   18;
			$data['remark']     =   '';//订单备注
			$data['countRoom']  =   $body['quantity'];//房间总数
			$data['created']    =   date('Y-m-d H:i:s',time());//订单生成时间
			$data['payType']    =   'PP';
			if(isset($body['orderStatus'])&&$body['orderStatus']=='66'){
				$data['status']=66;
				$data['paid']=0;
				$arr['body']['orderStatus'] = 66;
				$arr['body']['returnCode'] = 0;
				$arr['body']['returnDescript'] = '预订成功';
				$arr['body']['interFaceAmount'] = $body['costAmount'];
				//判断订单是否存在
				$qunaer_order=$this->qm->ordersModel->fetchRow("select id from qm_orders where orderId='".$body['orderID']."' and hotelId='".$body['hotelCode']."' and type='".$body['sourceID']."' and roomId=".$body['roomTypeId']);
				if($qunaer_order){$res = $this->qm->ordersModel->update($data,"id=".$qunaer_order['id']);}
				else{$res = $this->qm->ordersModel->insert($data);}
				
				if($res){$arr['body']['hotelConfirmNo']=$res;}
				else{$arr['body']['hotelConfirmNo']=$qunaer_order['id'];}
			}else{
				$data['paid']=$price;
				
				$this->loadApi('orderapi');
				$orderapi = new orderapi();
				$ckord=$orderapi->booking($body['hotelCode'],18,'18581850569',$name,$body['roomTypeId'],$body['quantity'],$body['orderID'],$body['effectDate'],$body['departure']);
				if($ckord){
					$data['status']=1;
					$data['qmorderId']=$ckord['orderId'];
					$data['commission']=$ckord['commission'];
					//判断订单是否存在
					$qunaer_order=$this->qm->ordersModel->fetchRow("select id from qm_orders where orderId='".$body['orderID']."' and hotelId='".$body['hotelCode']."' and type='".$body['sourceID']."' and roomId=".$body['roomTypeId']);
					if($qunaer_order){$res = $this->qm->ordersModel->update($data,"id=".$qunaer_order['id']);}
					else{$res = $this->qm->ordersModel->insert($data);}
					
					if($res){$arr['body']['hotelConfirmNo']=$res;}
					else{$arr['body']['hotelConfirmNo']=$qunaer_order['id'];}
					
					$arr['body']['orderStatus'] = 3;
					$arr['body']['returnCode'] = 0;
					$arr['body']['returnDescript'] = '预订成功';
					$arr['body']['interFaceAmount'] = $body['costAmount'];
				}else{
					$nowtime=time();$limitime=strtotime($data['created'])+8;//超时判断
					if($nowtime>$limitime){$data['status']=101;}else{$data['status']=100;}
					//判断订单是否存在
					$qunaer_order=$this->qm->ordersModel->fetchRow("select id from qm_orders where orderId='".$body['orderID']."' and hotelId='".$body['hotelCode']."' and type='".$body['sourceID']."' and roomId=".$body['roomTypeId']);
					if($qunaer_order){$res = $this->qm->ordersModel->update($data,"id=".$qunaer_order['id']);}
					else{$res = $this->qm->ordersModel->insert($data);}
					
					$arr['body']['returnCode'] = 999999;
					$arr['body']['returnDescript'] = '下单失败';
					$arr['body']['orderStatus'] = 4;
					$arr['body']['interFaceAmount'] = 0;
					$arr['body']['hotelConfirmNo']=0;
				}
			}
		}else{
			$string="";
			if(!$arRoom){$string.="房间不够";}if(!$arPrice){$string.=",价格不正确";}
			$arr['body']['returnCode'] = 999999;
            $arr['body']['returnDescript'] = $string;
            $arr['body']['orderStatus'] = 4;
            $arr['body']['interFaceAmount'] = 0;
            $arr['body']['hotelConfirmNo']=0;
		}
        echo json_encode($arr);
		
		$logs="调用方法：DomesticSubmitNewHotelOrderr\n返回数据：".json_encode($arr)."\r\n接收数据：".json_encode($array);
		$this->setLogs($logs,"/data/Logs/order/");
		
		$this->ThotelStatus($body['hotelCode'],$body['roomTypeId'],$body['effectDate'],$body['departure']);
		exit;
    }
	
	//查询房量
	function selectRooms($hid=0,$rid=0,$sta='',$end='',$roomNumber=0){
		$this->loadModel('qm','roombatch');
		$sql="select maxNum from qm_roombatch where hid='".$hid."' and rid='".$rid."' and date between '".$sta."'";
		$sql.=" and '".date('Y-m-d',(strtotime($end)-24*3600))."' order by maxNum asc";
		$re=$this->qm->roombatchModel->fetchRow($sql);
		if($re&&$roomNumber<=$re['maxNum']){return 1;}
		return 0;
	}
	
	//更新订单时间内的 房态房价 推送////
	function ThotelStatus($hid=0,$rid=0,$sta='',$end=''){
		$this->loadApi('orderapi');
		$orderapi = new orderapi();
		
		$resout=$orderapi->roombatch($hid,$rid,$sta,$end);
		if(!empty($resout['list']['room']['roomDatelist'])){
			$this->SP($resout['list']['room']['roomDatelist'],$hid,$rid);
		}
	}
	//房态价格 存库  发送OSII
	function SP($resource,$hid,$rid){
		$this->loadModel('qm','roombatch');
		
		$statusArr=$priceArr=array();
		foreach($resource as $ka=>$va){
			$data['hid'] = $hid;
			$data['rid'] = $rid;
			$data['date'] = !empty($va['@attributes']['date'])?$va['@attributes']['date']:'';
			$data['price'] = !empty($va['@attributes']['price'])?$va['@attributes']['price']:0;
			$data['roomStatus'] = !empty($va['@attributes']['roomStatus'])?$va['@attributes']['roomStatus']:0;
			$data['maxNum'] = !empty($va['@attributes']['maxNum'])?$va['@attributes']['maxNum']:0;
			$data['paymentMode'] = !empty($va['@attributes']['paymentMode'])?$va['@attributes']['paymentMode']:0;
			$data['redFree'] = !empty($va['@attributes']['redFree'])?$va['@attributes']['redFree']:0;
			$data['commentFree'] = !empty($va['@attributes']['commentFree'])?$va['@attributes']['commentFree']:0;
			$data['breakfast'] = !empty($va['@attributes']['breakfast'])?$va['@attributes']['breakfast']:'不含早';
			$data['created'] = date('Y-m-d H:i:s',time());
			
			$rq=$this->qm->roombatchModel->fetchRow("select id from qm_roombatch where hid=".$hid." and rid=".$rid." and date='".@$va['@attributes']['date']."'");
			if($rq){$qs=$this->qm->roombatchModel->update($data,"id=".$rq['id']);}
			else{$qs=$this->qm->roombatchModel->insert($data);}
			
			$statusArr[$ka]['maxNum']=!empty($va['@attributes']['maxNum'])?$va['@attributes']['maxNum']:0;
			$statusArr[$ka]['date']=!empty($va['@attributes']['date'])?$va['@attributes']['date']:'';
			$statusArr[$ka]['roomStatus']=!empty($va['@attributes']['roomStatus'])?$va['@attributes']['roomStatus']:0;
			
			$priceArr[$ka]['date']=!empty($va['@attributes']['date'])?$va['@attributes']['date']:'';
			$priceArr[$ka]['price']=!empty($va['@attributes']['price'])?$va['@attributes']['price']:0;
			$breakfast=0;
			if(!empty($va['@attributes']['breakfast'])&&($va['@attributes']['breakfast']=="1份"||$va['@attributes']['breakfast']=="含早餐")){
				$breakfast=1;
			}elseif(!empty($va['@attributes']['breakfast'])&&$va['@attributes']['breakfast']=="2份"){
				$breakfast=2;
			}
			$priceArr[$ka]['breakfast']=$breakfast;
		}
		$this->MoStatus($statusArr,$hid,$rid,2);
		$this->MoPrice($priceArr,$hid,$rid);
	}
	//房态推送  @type 1关闭 否则 原状态
	function MoStatus($array=array(),$hid=0,$rid=0,$type=1){
		$this->loadApi('toQmgHotelLog');
		$toQmgHotelLog = new toQmgHotelLog();
		
		$body['startDate']=$body['endDate']="";
		$body['hotelCode']=$hid;
		$body['roomID']=$rid;
		$body['sourceId']=2;
		$body['editer']='qmg';$body['roomInfoList']=array();
		if($array){
			$body['startDate']=$array[0]['date'];
			$body['endDate']=$array[(count($array)-1)]['date'];
			
			$timeDa=$timeDb=$arrSort=array();$count=(strtotime($body['endDate'])-strtotime($body['startDate']))/24/3600;
			for($j=0;$j<$count;$j++){
				$timeDa[]=date('Y-m-d',(strtotime($body['startDate'])+$j*24*3600));
			}
			foreach($array as $k=>$v){$timeDb[]=$v['date'];}
			foreach($timeDa as $k=>$v){
				if(!in_array($v,$timeDb)){
					$count++;
					$array[$count]['maxNum']=0;
					$array[$count]['date']=$v;
					$array[$count]['roomStatus']=0;
				}
			}
			foreach($array AS $uniqid => $row){$arrSort[] = $row['date'];}
			array_multisort($arrSort, SORT_ASC, $array);
			
			$i=0;
			foreach($array as $k=>$v){
				$body['roomInfoList'][$i]['fl']=$v['maxNum'];
				$body['roomInfoList'][$i]['setToDate']=$v['date'];
				$body['roomInfoList'][$i]['changeDefault']='T';
				$body['roomInfoList'][$i]['holdDeadline']='9999';
				$body['roomInfoList'][$i]['note']='';
				$body['roomInfoList'][$i]['reserveTime']='0';
				$body['roomInfoList'][$i]['roomstatus']=$type!=1&&$v['roomStatus']==1&&$v['maxNum']>0?'G':'N';
				$body['roomInfoList'][$i]['roomsInv']='0';
				$body['roomInfoList'][$i]['guarantee']='';
				$body['roomInfoList'][$i]['guaranteeLCT']=4;
				$body['roomInfoList'][$i]['prepayLCT']=23988;
				$body['roomInfoList'][$i]['allNeedGuarantee']='F';
				$body['roomInfoList'][$i]['lateReserveTime']=0;
				$body['roomInfoList'][$i]['deductType']='C';
				$body['roomInfoList'][$i]['blanceType']='PP';
				$body['roomInfoList'][$i]['restorable']='F';
				$body['roomInfoList'][$i]['checkType']='C';
				$body['roomInfoList'][$i]['userLimited']='9999';
				$i++;
			}
			$toQmgHotelLog->roomstatus($body);
		}
	}
	
	//价格推送
	function MoPrice($array=array(),$hid=0,$rid=0){
		$this->loadApi('toQmgHotelLog');
		$toQmgHotelLog = new toQmgHotelLog();
		
		if($array){
			$startDate=$array[0]['date'];
			$endDate=$array[(count($array)-1)]['date'];
			
			$timeDa=$timeDb=$arrSort=array();$count=(strtotime($endDate)-strtotime($startDate))/24/3600;
			for($j=0;$j<$count;$j++){
				$timeDa[]=date('Y-m-d',(strtotime($startDate)+$j*24*3600));
			}
			foreach($array as $k=>$v){$timeDb[]=$v['date'];}
			foreach($timeDa as $k=>$v){
				if(!in_array($v,$timeDb)){
					$count++;
					$array[$count]['price']=0;
					$array[$count]['date']=$v;
					$array[$count]['breakfast']=0;
				}
			}
			foreach($array AS $uniqid => $row){$arrSort[] = $row['date'];}
			array_multisort($arrSort, SORT_ASC, $array);
			$body = array('setRoomPriceItems' => array());
			$body['setRoomPriceItems'][0]['priceInfos'] = array();
			$body['setRoomPriceItems'][0]['hotelId'] = $hid;
			$body['setRoomPriceItems'][0]['sourceId'] = 2;
			$body['setRoomPriceItems'][0]['roomId'] = $rid;
			$body['setRoomPriceItems'][0]['startDate'] = $startDate.'T00:00:00';
			$body['setRoomPriceItems'][0]['endDate'] = $endDate.'T00:00:00';
			$body['setRoomPriceItems'][0]['currency'] = "CNY";
			$i=0;
			foreach($array as $k=>$v){
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['prices'] = array();
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['prices'][0]['amountBeforeTaxFee'] = $v['price'];
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['prices'][0]['amountAfterTaxFee'] = $v['price'];
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['prices'][0]['costAmountBeforeTaxFee'] = $v['price'];
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['prices'][0]['costAmountAfterTaxFee'] = $v['price'];
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['prices'][0]['day'] = 0;
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['stays'] = 0;
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['blanceType'] = "PP";
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['priceType'] = "Cost";
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['breakfast'] = $v['breakfast'];
				$body['setRoomPriceItems'][0]['priceInfos'][$i]['isCancel'] = 0;
				$i++;
			}
			$toQmgHotelLog->typePrice($body);
		}
	}
}